package com.bidevalution.business.common;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * 计算文件MD5
 * @author lance
 */
public class AnalysisFileMd5Util {
    private AnalysisFileMd5Util(){}
    private static final Logger log = LoggerFactory.getLogger(AnalysisFileMd5Util.class);

    private static final String[] STR_HEX = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 分块计算MD5
     *
     * @param path 路径
     * @return MD5
     */
    public static String getMD5Three(String path) {
        byte[] buffer = new byte[8192];
        try(FileInputStream fis = new FileInputStream(new File(path));) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            int len;
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            byte[] b = md.digest();
            return byteToStr(b).toUpperCase();
        } catch (Exception e) {
            log.error("LOG[]getMD5Three[]{}", e);
        }
        return "";
    }

    /**
     * 单块计算MD5
     *
     * @param path 路径
     * @return MD5
     */
    public static String getMd5ByFile(String path) {
        return getMd5ByFile(new File(path));
    }

    /**
     * 单块计算MD5
     *
     * @param file 文件对象
     * @return MD5
     */
    public static String getMd5ByFile(File file) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(FileUtils.readFileToByteArray(file));
            return byteToStr(md.digest());
        } catch (Exception e) {
            log.error("LOG[]getMd5ByFile[]{}", e);
        }
        return "";
    }

    private static String byteToStr(byte[] b){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            int d = b[i];
            if (d < 0) {
                d += 256;
            }
            sb.append(STR_HEX[d / 16] + STR_HEX[d % 16]);
        }
        return sb.toString();
    }
}
